package net.jeeframework.fileuplod.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import net.coobird.thumbnailator.Thumbnailator;
import net.jeeframework.fileuplod.FileInfo;
import net.jeeframework.fileuplod.IFileSystem;
import net.jeeframework.fileuplod.util.FileSystemConfig;
import net.jeeframework.fileuplod.util.FileSystemValidator;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 本地文件系统接口
 * 
 * @author kai
 * 
 */
public class LocalFileSystem implements IFileSystem {

	private static final Log log = LogFactory.getLog(LocalFileSystem.class);

	public FileInfo save(File file, String filename) {
		return save(file, filename, FileSystemConfig.getSaveDir());
	}

	public FileInfo save(File file, String filename, String saveDir) {
		if (file == null) {
			log.error("the file is null exception");
		}

		if (!FileSystemValidator.isFileAllowed(filename)) {
			log.error("文件类型验证失败：文件类型不是允许类型");
		}

		FileInfo info = new FileInfo(filename);

		if (null != saveDir) {
			String path = saveDir + File.separator + info.getFileId();
			info.setPath(path);
		}

		try {
			FileUtils.copyFile(file, new File(info.getPath()), true);
		} catch (IOException e) {
			log.error("复制文件出错：", e);
		}

		return info;
	}

	public FileInfo saveThumbnail(File file, String filename, int width, int height) {
		return saveThumbnail(file, filename, FileSystemConfig.getSaveDir(), width, height);
	}

	public FileInfo saveThumbnail(File file, String filename, String saveDir, int width, int height) {

		FileInfo info = new FileInfo(filename);

		String path = saveDir + File.separator + info.getFileId();
		info.setPath(path);

		try {
			Thumbnailator.createThumbnail(new FileInputStream(file), new FileOutputStream(new File(info.getPath())), width, height);
		} catch (FileNotFoundException e) {
			log.error("没有找到对应的文件：", e);
		} catch (IOException e) {
			log.error("文件读取异常：", e);
		}

		return info;
	}

}
